package com.example.demo.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* @comments
* @author  zg
* @date 2018年8月29日 
*/
public class HttpUtils {

	public static String sendPost(String reqUrl, String content, boolean isForm) throws Exception{
		String resContent = null;
		
		HttpURLConnection conn = null;
		OutputStream out = null;
		InputStream in = null;
		BufferedReader reader = null;
		try {
			URL url = new URL(reqUrl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(10000);
			conn.setReadTimeout(60000);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setInstanceFollowRedirects(false);//是否自动处理重定向
			conn.setRequestMethod("POST");
			conn.setRequestProperty("connection", "Keep-Alive");
            if(isForm){
            	conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");//传递参数使用 &链接的表单提交方式
            }else{
            	conn.setRequestProperty("Content-Type", "application/json");
            }
            conn.connect();
            out = conn.getOutputStream();
            //发送请求数据
			out.write(content.getBytes("UTF-8"));
			out.flush();
			out.close();
			//接收返回数据
			int resCode = conn.getResponseCode();
			if(resCode == 200){
				in = conn.getInputStream();
				reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
				resContent = reader.readLine();
			}else{
				resContent = "error:"+resCode;
				System.out.println("服务器返回码："+resCode);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally{
			if(reader != null){
				reader.close();
			}
			if(out != null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(in != null){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(conn != null){
				conn.disconnect();
			}
		}
		return resContent;
	}
}
